package com.jastar.android.game.go;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AIPlayer {
    private static final int EMPTY = 0;
    private static final int HUMAN = 1; // 黑棋
    private static final int AI = 2;    // 白棋
    private final Random random = new Random();

    public interface BoardState {
        int[][] getBoard();

        boolean isValidMove(int row, int col);
    }

    public int[] makeMove(BoardState boardState) {
        int[][] board = boardState.getBoard();
        List<int[]> candidates = new ArrayList<>();

        // 第一步：寻找最佳候选位置
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == EMPTY && isNearbyStone(board, i, j)) {
                    int score = evaluatePosition(board, i, j);
                    if (score > 0) candidates.add(new int[]{i, j, score});
                }
            }
        }

        // 第二步：选择最佳候选位置
        if (!candidates.isEmpty()) {
            candidates.sort((a, b) -> b[2] - a[2]); // 按评分降序排序
            int maxScore = candidates.get(0)[2];
            List<int[]> bestMoves = new ArrayList<>();
            for (int[] c : candidates) {
                if (c[2] == maxScore) bestMoves.add(c);
            }
            return bestMoves.get(random.nextInt(bestMoves.size()));
        }

        // 第三步：没有合适位置时随机落子（优先中心区域）
        return randomMove(boardState);
    }

    // 检查附近是否有棋子（围棋通常不会在空旷处落子）
    private boolean isNearbyStone(int[][] board, int row, int col) {
        for (int i = Math.max(0, row - 2); i <= Math.min(board.length - 1, row + 2); i++) {
            for (int j = Math.max(0, col - 2); j <= Math.min(board[0].length - 1, col + 2); j++) {
                if (board[i][j] != EMPTY) {
                    return true;
                }
            }
        }
        return false;
    }

    private int evaluatePosition(int[][] board, int row, int col) {
        int score = 0;

        // 简单评估规则（可扩展）
        score += evaluateDirection(board, row, col, 0, 1);  // 水平
        score += evaluateDirection(board, row, col, 1, 0);  // 垂直
        score += evaluateDirection(board, row, col, 1, 1);  // 主对角线
        score += evaluateDirection(board, row, col, 1, -1); // 副对角线

        // 优先占据星位和天元
        if ((row == 3 || row == 9 || row == 15) && (col == 3 || col == 9 || col == 15)) {
            score += 100;
        }

        return score;
    }

    private int evaluateDirection(int[][] board, int row, int col, int dx, int dy) {
        int aiCount = 0;
        int humanCount = 0;
        int aiOpenEnds = 0;
        int humanOpenEnds = 0;

        // 模拟落子
        int[][] tempBoard = copyBoard(board);
        tempBoard[row][col] = AI;

        // 双向检测
        for (int i = -4; i <= 4; i++) {
            int r = row + i * dx;
            int c = col + i * dy;

            if (r < 0 || r >= board.length || c < 0 || c >= board[0].length) continue;

            if (tempBoard[r][c] == AI) {
                aiCount++;
            } else if (tempBoard[r][c] == HUMAN) {
                humanCount++;
            }
        }

        // 评分规则（围棋比五子棋复杂，这里只是简化版本）
        if (aiCount >= 4) return 500;     // 形成长连
        if (humanCount >= 4) return 450;  // 阻止对方长连
        if (aiCount == 3) return 200;     // 形成三连
        if (humanCount == 3) return 180;  // 阻止对方三连

        // 边角位置稍微加分
        if ((row <= 2 || row >= 16 || col <= 2 || col >= 16)) {
            return 50;
        }

        return aiCount * 10;
    }

    private int[][] copyBoard(int[][] board) {
        int[][] copy = new int[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            System.arraycopy(board[i], 0, copy[i], 0, board[i].length);
        }
        return copy;
    }

    private int[] randomMove(BoardState boardState) {
        List<int[]> emptyCells = new ArrayList<>();
        int[][] board = boardState.getBoard();

        // 优先中心区域
        for (int i = 7; i <= 11; i++) {
            for (int j = 7; j <= 11; j++) {
                if (boardState.isValidMove(i, j)) {
                    emptyCells.add(new int[]{i, j});
                }
            }
        }

        if (!emptyCells.isEmpty()) {
            return emptyCells.get(random.nextInt(emptyCells.size()));
        }

        // 然后是整个棋盘
        // 修改第133行的随机落子逻辑，适应13x13棋盘
        // 将原来的7-11范围改为3-9
        for (int i = 3; i <= 9; i++) {
            for (int j = 3; j <= 9; j++) {
                if (boardState.isValidMove(i, j)) {
                    emptyCells.add(new int[]{i, j});
                }
            }
        }

        return emptyCells.isEmpty() ? new int[]{-1, -1} : emptyCells.get(random.nextInt(emptyCells.size()));
    }
}